package com.junyuan.fxf_pad.activity.fragment;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.baidu.apistore.sdk.ApiCallBack;
import com.baidu.apistore.sdk.ApiStoreSDK;
import com.junyuan.fxf_pad.R;
import com.junyuan.fxf_pad.utils.BleUtils;
import com.junyuan.fxf_pad.utils.Consts;
import com.junyuan.fxf_pad.utils.GetWeather;
import com.junyuan.fxf_pad.utils.Rotate3dAnimation;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;


public class MoveFragment extends Fragment implements View.OnClickListener {
    ImageView iv_forward, iv_stop, iv_back, iv_left, iv_right;
    LinearLayout llweather;

    Button iv_weather, iv_ble, iv_touch;
    boolean isScaled_weather = false;
    boolean isScaled_ble = false;
    boolean isScaled_touch = false;
    public static boolean isConnected = false;

    String httpUrl = "http://apis.baidu.com/apistore/weatherservice/cityname";

    String temp;

    MyBroadCastReceiver myBroadCastReceiver;

    ArrayList<String> weather;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == Consts.GET_WEATHER_SUCCESS) {
                weather = msg.getData().getStringArrayList("weather");
                Log.d("mytag", "得到天气" + weather.get(0) + "温度：" + weather.get(1));
                temp = weather.get(1) + "°C";
            }
            if (msg.what == Consts.GET_LOCATION_SUCCESS) {
                Bundle bundle = msg.getData();
                String city = bundle.getString("city");
                city = city.replace("市", "");
                Log.d("mytag", city);
                GetWeather getWeather = new GetWeather(handler);
                weather = getWeather.getWeather(httpUrl, city);
            }

            if (msg.what == Consts.Ble_CONNECTED) {
                scaleAnimation(iv_ble);
            }
            if (msg.what == Consts.Ble_DISCONNECTED) {
                scaleAnimation(iv_ble);
            }
            if (msg.what == Consts.TOUCH_ON) {
                isScaled_touch = false;
                scaleAnimation(iv_touch);
            }
            if (msg.what == Consts.TOUCH_OFF) {
                isScaled_touch = true;
                scaleAnimation(iv_touch);
            }
            return false;
        }
    });


//    //蓝牙连接部分
//    private BleService mBleService;
//    private boolean mIsBind;
//    private BluetoothDevice mDevice;
//
//    private ServiceConnection serviceConnection = new ServiceConnection() {
//        @Override
//        public void onServiceConnected(ComponentName name, IBinder service) {
//            mBleService = ((BleService.LocalBinder) service).getService();
//            mIsBind = true;
//            if (mBleService.initialize()) {
//                if (mBleService.enableBluetooth(true)) {
////                    mBleService.scanLeDevice(true);
//                    Toast.makeText(getContext(), "Bluetooth was opened", Toast.LENGTH_SHORT).show();
//                }
//            } else {
//                Toast.makeText(getContext(), "not support Bluetooth", Toast.LENGTH_SHORT).show();
//            }
//        }
//
//        @Override
//        public void onServiceDisconnected(ComponentName name) {
//            mBleService = null;
//            mIsBind = false;
//        }
//    };

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_move, null);
        initView(view);
//        ApiStoreSDK.init(getActivity().getApplicationContext(), "8979790e60699e9682cf8bb238af045a");


//        //根据屏幕宽度header自适应高度
//        int width = getActivity().getWindowManager().getDefaultDisplay().getWidth();
//        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, width / 2);
//        iv_header.setLayoutParams(params);
        getLocation();

        BleUtils.getInstance().initBle(getContext());


        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        myBroadCastReceiver = new MyBroadCastReceiver();
        IntentFilter filter = new IntentFilter("BackData");
        filter.addAction("BackData");
        filter.addAction("Ble_CONNECTED");
        filter.addAction("Ble_DISCONNECTED");
        getContext().registerReceiver(myBroadCastReceiver, filter);
        isScaled_weather = false;
        if (isConnected) {
            iv_ble.setBackgroundResource(R.drawable.move_button);
            iv_ble.setText("已开启");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_weather:
                if (!isScaled_weather) {
                    scaleAnimation(iv_weather);
                }
                break;
            case R.id.iv_ble:
                linkBle();
                break;
            case R.id.iv_touch:
                scaleAnimation(iv_touch);
                if (!isScaled_touch) {
                    BleUtils.getInstance().sendData("#1", 0);
                } else if (isScaled_touch) {
                    BleUtils.getInstance().sendData("#0", 0);
                }

                break;
            case R.id.iv_forward:
                BleUtils.getInstance().sendData("#R2", 0);
                break;
            case R.id.iv_stop:
                if (iv_stop.isSelected()) {
                    iv_stop.setSelected(false);
                    BleUtils.getInstance().sendData("#S4", 0);
                } else {
                    iv_stop.setSelected(true);
                    BleUtils.getInstance().sendData("#S4", 0);
                }
                break;
            case R.id.iv_back:
                BleUtils.getInstance().sendData("#R1", 0);
                break;
            case R.id.iv_left:
                BleUtils.getInstance().sendData("#R3", 0);
                break;
            case R.id.iv_right:
                BleUtils.getInstance().sendData("#R4", 0);
                break;
        }
    }


    /**
     * 连接蓝牙
     */
    private void linkBle() {
        if (isConnected) {
            BleUtils.getInstance().disconnect();
        } else {
            BleUtils.getInstance().scanBleDevices(true);
        }
    }

    /**
     * 通过位置，获得天气(百度Api)
     */
    private void getLocation() {
        // 获取位置管理服务
        LocationManager locationManager;
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getContext().getSystemService(serviceName);
        // 查找到服务信息
        Criteria criteria = new Criteria();
        //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略，Criteria.ACCURACY_FINE则比较精细
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        //设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费
        criteria.setCostAllowed(false);
        //设置是否需要方位信息
        criteria.setBearingRequired(false);
        //设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String provider = locationManager.getBestProvider(criteria, true); // 获取GPS信息
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(provider); // 通过GPS获取位置
        if (location != null) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            Log.d("mytag", "经纬度为" + latitude + "   " + longitude);
            String url = "http://apis.baidu.com/wxlink/here/here";
            String httpArg = "?lat=" + latitude + "&lng=" + longitude + "&cst=1";
            url = url + httpArg;
            Log.d("123", url);

            ApiStoreSDK.execute(url, ApiStoreSDK.GET, null, new ApiCallBack() {
                @Override
                public void onSuccess(int i, String s) {
                    super.onSuccess(i, s);
                    Log.d("mytag", "定位请求返回的json:" + s);
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        int status = jsonObject.getInt("code");
                        if (status == 10000) {
                            JSONArray jsonArray = jsonObject.getJSONArray("result");
                            JSONObject jsonObject1 = jsonArray.getJSONObject(1);
                            String city = jsonObject1.getString("DistrictName");
                            Log.d("mytag", city);
                            Message message = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("city", city);
                            message.what = Consts.GET_LOCATION_SUCCESS;
                            message.setData(bundle);
                            handler.sendMessage(message);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onError(int i, String s, Exception e) {
                    super.onError(i, s, e);
                    Log.d("mytag", "获取城市错误" + "i:" + i + "e:" + e + "s:" + s);
                }
            });
        }
    }


    /**
     * 3D旋转动画
     *
     * @param v 需要旋转的空间
     */
    public void scaleAnimation(final Button v) {
        Rotate3dAnimation animation = new Rotate3dAnimation(0, 180, v.getWidth() / 2, v.getHeight() / 2, 0, true);
        animation.setDuration(500);
        animation.setInterpolator(new LinearInterpolator());
        v.startAnimation(animation);

        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                switch (v.getId()) {
                    case R.id.iv_weather:
                        v.setBackgroundResource(R.drawable.move_button);
//                        getLocation();
                        if (temp != null) {
                            iv_weather.setText(temp);
                            iv_weather.setTextColor(Color.WHITE);
                        }
                        isScaled_weather = true;
                        break;
                    case R.id.iv_ble:
                        if (isConnected) {
                            v.setBackgroundResource(R.drawable.move_button);
                            v.setText("已开启");
                            isScaled_ble = true;
                        } else {
                            v.setBackgroundResource(R.drawable.move_ble);
                            v.setText("");
                            isScaled_ble = false;
                        }
                        break;
                    case R.id.iv_touch:
                        if (!isScaled_touch) {
                            v.setBackgroundResource(R.drawable.move_button);
                            v.setText("已开启");
                            isScaled_touch = true;
                        } else {
                            v.setBackgroundResource(R.drawable.move_touch);
                            v.setText("");
                            isScaled_touch = false;
                        }
                        break;
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }


    @Override
    public void onPause() {
        super.onPause();
        getContext().unregisterReceiver(myBroadCastReceiver);
        Log.d("123", "MoveFragmentDestory");
        isConnected = false;
    }

    public class MyBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case "BackData":
                    String backData = intent.getStringExtra("BackData");
                    Log.d("mytag", "MoveFragment的广播接收到：" + backData);
                    Message message = new Message();
                    if (backData.equals("aa")) {
                        message.what = Consts.TOUCH_ON;
                        handler.sendMessage(message);
                    } else if (backData.equals("bb")) {
                        message.what = Consts.TOUCH_OFF;
                        handler.sendMessage(message);
                    }
                    break;
                case "Ble_DISCONNECTED":
                    isConnected = false;
                    handler.sendEmptyMessage(Consts.Ble_DISCONNECTED);
                    break;
                case "Ble_CONNECTED":
                    isConnected = true;
                    handler.sendEmptyMessage(Consts.Ble_CONNECTED);
                    break;
            }
        }
    }

    private void initView(View view) {
//        iv_header = (ImageView) view.findViewById(iv_header);
        iv_weather = (Button) view.findViewById(R.id.iv_weather);
        iv_ble = (Button) view.findViewById(R.id.iv_ble);
        iv_touch = (Button) view.findViewById(R.id.iv_touch);
        iv_forward = (ImageView) view.findViewById(R.id.iv_forward);
        iv_stop = (ImageView) view.findViewById(R.id.iv_stop);
        iv_back = (ImageView) view.findViewById(R.id.iv_back);
        iv_left = (ImageView) view.findViewById(R.id.iv_left);
        iv_right = (ImageView) view.findViewById(R.id.iv_right);
        llweather = (LinearLayout) view.findViewById(R.id.ll_weather);

//        iv_header.setOnClickListener(this);
        iv_weather.setOnClickListener(this);
        iv_ble.setOnClickListener(this);
        iv_touch.setOnClickListener(this);
        iv_forward.setOnClickListener(this);
        iv_stop.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        iv_left.setOnClickListener(this);
        iv_right.setOnClickListener(this);
    }
}
